<?php
include("include/conn.php");
require('include/Smarty/libs/Smarty.class.php');

$bhatthiParty = array();
$fineTotal    = 0;
$amountTotal  = 0;
$total        = array();

$selectBhatthiParty = "SELECT bhatthiPartyId, bhatthipartyName 
                         FROM bhatthiparty";
$selectBhatthiPartyRes = mysql_query($selectBhatthiParty);
$a = 0;
while($row = mysql_fetch_assoc($selectBhatthiPartyRes))
{
  $bhatthiParty[$a]['id']       = $row['bhatthiPartyId'];
  $bhatthiParty[$a]['name']     = $row['bhatthipartyName'];
  $bhatthiParty[$a]['drFine']   = 0;
  $bhatthiParty[$a]['crFine']   = 0;
  $bhatthiParty[$a]['drAmount'] = 0;
  $bhatthiParty[$a]['crAmount'] = 0;
  
	$bhatthiBookDetail = "SELECT bhatthibookdetail.fine, bhatthibookdetail.amount, bhatthibookdetail.CrDr
	                        FROM bhatthibook
	                        JOIN bhatthibookdetail ON bhatthibookdetail.bhatthiBookId = bhatthibook.bhatthiBookId
	                       WHERE bhatthibook.bhatthiPartyId = ".$row['bhatthiPartyId']."
	                       ORDER BY bhatthibook.bhatthiDate, bhatthibookdetail.bhatthiBookDetailId";
	$bhatthiBookDetailRes = mysql_query($bhatthiBookDetail);
	while($bhatthiRow = mysql_fetch_assoc($bhatthiBookDetailRes))
	{
		if($bhatthiRow['CrDr'] == "Dr")
		{
			$bhatthiParty[$a]['drFine']   += $bhatthiRow['fine'];
			$bhatthiParty[$a]['drAmount'] += $bhatthiRow['amount'];
		}
		else
		{
			$bhatthiParty[$a]['crFine']   += $bhatthiRow['fine'];
			$bhatthiParty[$a]['crAmount'] += $bhatthiRow['amount'];
		}
		$total[$a]['fine']   = ($bhatthiParty[$a]['drFine'] - $bhatthiParty[$a]['crFine']);
	  $total[$a]['amount'] = ($bhatthiParty[$a]['drAmount'] - $bhatthiParty[$a]['crAmount']);
	}
	$fineTotal   += ($bhatthiParty[$a]['drFine'] - $bhatthiParty[$a]['crFine']);
	$amountTotal += $bhatthiParty[$a]['drAmount'] - $bhatthiParty[$a]['crAmount'];
	$a++;
}

$smarty = new Smarty;
require("bottom.php");
$smarty->assign("l_bhatthipartyName",$l_bhatthipartyName);
$smarty->assign("l_fine",$l_fine);
$smarty->assign("l_amount",$l_amount);
$smarty->assign("l_total",$l_total);

$smarty->assign("bhatthiParty",$bhatthiParty);
$smarty->assign("total",$total);
$smarty->assign("fineTotal",$fineTotal);
$smarty->assign("amountTotal",$amountTotal);
$smarty->display("bhatthiSummary.tpl");
?>